//
//  CommentAndPriaseVIew.m
//  TodatPlay
//
//  Created by dllo on 16/9/23.
//  Copyright © 2016年 DM.C. All rights reserved.
//

#import "CommentAndPriaseVIew.h"
#import "SDAutoLayout.h"
#import "UIView+Frame.h"
#import "SceneObj.h"
#import "SceneUserlist.h"
#import "SceneCommentlist.h"
#import "SceneStorylist.h"
#import "SCeneCommentcountlist.h"
#import "ScenePraiseinfolist.h"
#import "ScenePraisecontainerlist.h"
#import "MLLinkLabel.h"
@interface CommentAndPriaseVIew ()<MLLinkLabelDelegate>
@property (nonatomic, strong) MLLinkLabel *likeLabel;
@property (nonatomic, strong) NSArray *likeItemsArray;
@property (nonatomic, strong) NSArray *commentItemsArray;
@property (nonatomic, strong) NSMutableArray *commentLabelsArray;
@property (nonatomic, strong) UIView *likeLineView;

@end

@implementation CommentAndPriaseVIew
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithRed:0.936 green:0.951 blue:0.982 alpha:1.000];
;
        self.commentLabelsArray = [NSMutableArray array];
        [self createComment];
        
    }
    return self;
}

- (void)createComment {
    
    _likeLabel = [MLLinkLabel new];
    _likeLabel.font = [UIFont systemFontOfSize:14];
    UIColor *heighlightColor = [UIColor colorWithRed:0.230 green:0.419 blue:1.000 alpha:1.000];
    _likeLabel.linkTextAttributes = @{NSForegroundColorAttributeName : heighlightColor};
    _likeLabel.isAttributedContent = YES;
    _likeLabel.delegate = self;
    [self addSubview:_likeLabel];
    
    
    // 创建横杠
    self.likeLineView = [UIView new];
    _likeLineView.backgroundColor = [UIColor colorWithWhite:0.800 alpha:1.000];
    [self addSubview:_likeLineView];

}
    

#pragma mark - 新的拼接
- (void)setCommentItemsArray:(NSArray *)commentItemsArray
{
    _commentItemsArray = commentItemsArray;
    
    long originalLabelsCount = self.commentLabelsArray.count;
    long needsToAddCount = commentItemsArray.count > originalLabelsCount ? (commentItemsArray.count - originalLabelsCount) : 0;
    for (int i = 0; i < needsToAddCount; i++) {
        MLLinkLabel *label = [MLLinkLabel new];
        UIColor *highLightColor = [UIColor colorWithRed:0.230 green:0.419 blue:1.000 alpha:1.000];
        label.linkTextAttributes = @{NSForegroundColorAttributeName : highLightColor};
        label.font = [UIFont systemFontOfSize:14];
        label.delegate = self;
        [self addSubview:label];
        [self.commentLabelsArray addObject:label];
    }
    
    for (int i = 0; i < commentItemsArray.count; i++) {
        SceneCommentlist *model = commentItemsArray[i];
        MLLinkLabel *label = self.commentLabelsArray[i];
        if (!model.attributedContent) {
            model.attributedContent = [self generateAttributedStringWithCommentItemModel:model];
        }
        label.attributedText = model.attributedContent;
    }
}

- (void)setLikeItemsArray:(NSArray *)likeItemsArray
{
    _likeItemsArray = likeItemsArray;
    
    NSTextAttachment *attach = [NSTextAttachment new];
    attach.image = [UIImage imageNamed:@"index_jilu_love_s"];
    attach.bounds = CGRectMake(0, -3, 16, 16);
    NSAttributedString *likeIcon = [NSAttributedString attributedStringWithAttachment:attach];
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:likeIcon];
    
    for (int i = 0; i < likeItemsArray.count; i++) {
        ScenePraiseinfolist *model = likeItemsArray[i];
        if (i > 0) {
            [attributedText appendAttributedString:[[NSAttributedString alloc] initWithString:@"，"]];
        }
        if (!model.attributedContent) {
            model.attributedContent = [self generateAttributedStringWithLikeItemModel:model];
        }
        [attributedText appendAttributedString:model.attributedContent];
    }
    
    _likeLabel.attributedText = [attributedText copy];
}

- (NSMutableArray *)commentLabelsArray
{
    if (!_commentLabelsArray) {
        _commentLabelsArray = [NSMutableArray new];
    }
    return _commentLabelsArray;
}

- (void)setupWithLikeItemsArray:(NSArray *)likeItemsArray commentItemsArray:(NSArray *)commentItemsArray
{
    self.likeItemsArray = likeItemsArray;
    self.commentItemsArray = commentItemsArray;
    
    if (self.commentLabelsArray.count) {
        [self.commentLabelsArray enumerateObjectsUsingBlock:^(UILabel *label, NSUInteger idx, BOOL *stop) {
            [label sd_clearAutoLayoutSettings];
            label.hidden = YES; //重用时先隐藏所有评论label，然后根据评论个数显示label
        }];
    }
    
    if (!commentItemsArray.count && !likeItemsArray.count) {
        self.fixedWidth = @(0); // 如果没有评论或者点赞，设置commentview的固定宽度为0（设置了fixedWith的控件将不再在自动布局过程中调整宽度）
        self.fixedHeight = @(0); // 如果没有评论或者点赞，设置commentview的固定高度为0（设置了fixedHeight的控件将不再在自动布局过程中调整高度）
        return;
    } else {
        self.fixedHeight = nil; // 取消固定宽度约束
        self.fixedWidth = nil; // 取消固定高度约束
    }
    
    CGFloat margin = 5;
    
    UIView *lastTopView = nil;
    
    if (likeItemsArray.count) {
        _likeLabel.sd_resetLayout
        .leftSpaceToView(self, margin)
        .rightSpaceToView(self, margin)
        .topSpaceToView(lastTopView, 10)
        .autoHeightRatio(0);
        
        lastTopView = _likeLabel;
    } else {
        _likeLabel.attributedText = nil;
        _likeLabel.sd_resetLayout
        .heightIs(0);
    }
    
    if (self.commentItemsArray.count && self.likeItemsArray.count) {
        _likeLineView.sd_resetLayout
        .leftSpaceToView(self, 5)
        .rightSpaceToView(self, 5)
        .heightIs(1)
        .topSpaceToView(lastTopView, 5);
        
        lastTopView = _likeLineView;
    } else {
        _likeLineView.sd_resetLayout.heightIs(0);
    }
    
    
    for (int i = 0; i < self.commentItemsArray.count; i++) {
        UILabel *label = (UILabel *)self.commentLabelsArray[i];
        label.hidden = NO;
        CGFloat topMargin = (i == 0 && likeItemsArray.count == 0) ? 10 : 5;
        label.sd_layout
        .leftSpaceToView(self, 8)
        .rightSpaceToView(self, 5)
        .topSpaceToView(lastTopView, topMargin)
        .autoHeightRatio(0);
        
        label.isAttributedContent = YES;

        lastTopView = label;
    }
    
    [self setupAutoHeightWithBottomView:lastTopView bottomMargin:10];
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
}

#pragma mark - private actions

- (NSMutableAttributedString *)generateAttributedStringWithCommentItemModel:(SceneCommentlist *)model
{
    NSInteger userId = model.userId;
    NSString *text = @"";
    NSMutableAttributedString *attString = nil;
    for (SceneUserlist *usetList in _userList) {
        if (userId == usetList.userId) {
            text = usetList.userName;
            text = [text stringByAppendingFormat:@": %@", model.context];
            
            NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:text];
            [attString setAttributes:@{NSLinkAttributeName : [NSString stringWithFormat:@"%ld", usetList.userId]} range:[text rangeOfString:usetList.userName]];
            return attString;
            
        }
    }
    return attString;
    
    
}

- (NSMutableAttributedString *)generateAttributedStringWithLikeItemModel:(ScenePraiseinfolist *)model
{
    NSString *text = model.userName;
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:text];
    UIColor *highLightColor = [UIColor colorWithRed:0.230 green:0.419 blue:1.000 alpha:1.000];
    [attString setAttributes:@{NSForegroundColorAttributeName : highLightColor, NSLinkAttributeName : [NSString stringWithFormat:@"%ld", model.userId]} range:[text rangeOfString:model.userName]];
    
    return attString;
}


#pragma mark - 关键字的点击方法
- (void)didClickLink:(MLLink *)link linkText:(NSString *)linkText linkLabel:(MLLinkLabel *)linkLabel
{
//    NSLog(@"%@",  linkText);
    for (SceneUserlist *usetList in _userList) {
        if ([usetList.userName isEqualToString:linkText]) {
            NSLog(@"评论的用户ID: %ld", usetList.userId);
#warning get UserID
        }
    }
    for (ScenePraiseinfolist *praise in _likeItemsArray) {
        if ([linkText isEqualToString:praise.userName]) {
            NSLog(@"点赞的用户ID: %ld", praise.userId);
    }

    }
    }


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
